<template>
  <div>
    <el-form ref="bjdForm" label-position='left' :model="tjForm" :rules="rulesTj" label-width="80px" size="mini">
      <el-row>
        <el-col :span="24">
          <el-form-item label="完工日期" prop="wgrq">
            <el-date-picker clearable
                            style="width: 100%"
                            v-model="tjForm.wgrq"
                            type="date"
                            value-format="yyyy-MM-dd"
                            placeholder="请选择完工日期">
            </el-date-picker>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="请上传深圳完工单" prop="tjFjId" label-width="140px">
            <el-upload
              ref="upload"
              class="upload-demo"
              :action="src"
              name="files"
              :on-success="handleSuccess"
              :on-error="handleError"
              :before-remove="handleRemove"
              :headers="uploadHeaders"
              accept=".xlsx, .xls"
              multiple
              :file-list="fjList"
            >
              <el-button size="small" type="primary"> <i class="el-icon-upload"></i> 点击上传</el-button>
              <div slot="tip" class="el-upload__tip">请上传深圳完工单</div>
            </el-upload>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-button :loading="buttonLoading" size="mini" plain type="primary" @click="handleTjWgd">点击生成</el-button>
      </el-row>
    </el-form>
  </div>
</template>

<script>
import { getToken } from '@/utils/auth'
import { szWgdToTjWgd } from '@/api/gd/ywdwgd'

export default {
  name: 'SzToTjWgd',
  data() {
    return {
      src: this.uploadSrc + '/gd/fj/file/batchUpload',
      uploadHeaders: { 'Authorization': 'Bearer ' + getToken() }, // 如果需要CSRF保护的话
      fjList: [],
      tjForm: {},
      buttonLoading: false,
      rulesTj: {
        wgrq: [
          { required: true, message: "请选择完工日期", trigger: "blur" }
        ],
        tjFjId: [
          { required: true, message: "请上传附件", trigger: "blur" }
        ]
      }
    }
  },
  created() {
    this.$set(this.tjForm, 'wgrq', this.formatDate(new Date()))
    this.$set(this, 'fjList', [])
  },
  methods: {
    // 处理生成天津完工单
    handleSuccess(response, file, fileList) {
      // 更新状态或者通知用户上传成功
      if (response !== null && response !== undefined) {
        // 获取当前的上传的附件id
        let fileIds = []
        fileList.forEach(item => {
          if (item.response !== undefined) {
            fileIds.push(item.response[0].fj)
          }
        })
        // 更新状态或者通知用户上传成功
        this.$message.success('上传成功');
        // 上传成功以后，将id设置
        this.tjForm.tjFjId = fileIds.toString()
      }
    },
    handleError(err, file) {
      // 处理错误并通知用户
      this.$message.error('上传失败：', err);
      this.$refs.upload.clearFiles()
    },
    handleRemove(file, fileList) {
      this.$refs.upload.clearFiles()
    },
    handleTjWgd() {
      if(this.tjForm.tjFjId) {
        let ids = this.tjForm.tjFjId.split(",")
        szWgdToTjWgd(this.tjForm, 'blob').then(res => {
          if (res !== null) {
            const binaryData = [];
            binaryData.push(res);
            let url = window.URL.createObjectURL(new Blob(binaryData, { type: 'application/octet-stream' }));
            const link = document.createElement('a');
            link.href = url
            if(ids.length === 1) {
              link.download = this.getTodayDate() + "_完工单.xlsx";
            }else {
              link.download = this.getTodayDate() + "_完工单.zip";
            }
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
          }
        })
      }else {
        this.$message.error("请上传附件！")
      }
    },
    getTodayDate() {
      const date = new Date();
      const year = date.getFullYear();
      const month = ('0' + (date.getMonth() + 1)).slice(-2);
      const day = ('0' + date.getDate()).slice(-2);
      return `${year}${month}${day}`;
    },
    formatDate(date) {
      const year = date.getFullYear();
      const month = (date.getMonth() + 1).toString().padStart(2, '0');
      const day = date.getDate().toString().padStart(2, '0');
      return `${year}-${month}-${day}`;
    }
  }
}
</script>

<style scoped>

</style>
